<?php
/**
 * Created by PhpStorm.
 * User: xiaofeng
 * motto: 现在的努力是为了小时候吹过的牛逼！
 * Date: 2020/1/7
 * Time: 14:35
 */
namespace app\admin\controller;

use app\common\model\mysql\AdminUser;
use think\captcha\facade\Captcha;
use think\facade\Session;
use think\facade\View;

class Login extends AdminBase {

    public function initialize()
    {
        if ($this->isLogin()){
            header("location:/admin/index/index");
        }
    }

    public function index(){

        return View::fetch();
    }

    public function verify(){
        return Captcha::create("abc");
    }

    public function md5(){
        echo md5('admin');
    }

    public function check(){

        if (!$this->request->isPost()){
            return show(config("status.error"),"请求方式错误");
        }
        $username = $this->request->param('username',"","trim");
        $password = $this->request->param('password',"","trim");
        $captcha = $this->request->param('captcha',"","trim");

        if (empty($username)||empty($password)||empty($captcha)){
            return show(config("status.error"),"参数不能为空");
        }

        if (!captcha_check($captcha)){
            return show(config("status.error"),"验证码错误");
        }

        $adminUserObj = new AdminUser();

        try{
        $adminUser = $adminUserObj->getAdminUserByUsername($username);

        if (empty($adminUser) || $adminUser->status != config("status.mysql.table_normal")){
             return show(config("status.error"),"不存在该用户");
        }

        $adminUser = $adminUser->toArray();

        if ($adminUser['password'] != $password){
            return show(config("status.error"),"密码错误");
        }

        // 需要记录信息到mysql
        $updateData = [
            "last_login_time"=>time(),
            "last_login_ip"=>request()->ip(),
            "update_time"=>time()
        ];

        $res = $adminUserObj->updateById($adminUser['id'],$updateData);

        if (empty($res)){
            return show(config("status.error"),"登录失败");
        }

        }catch (\Exception $e){
            return show(config("status.error"),"内部异常，登录失败",[],500);
        }
        //记录session

        session(config("admin.session_admin"),$adminUser);

        return show(config("status.success"),"登录成功");
    }
}
